package com.wanrue.tcc.recover;

import lombok.Setter;
import com.wanrue.tcc.exception.SystemException;
import org.quartz.Scheduler;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;

/**
 * 事务定时恢复
 * Created by changming.xie on 6/2/16.
 */
@Setter
public class ScheduledJob {

    private Scheduler scheduler;

    private TransactionRecovery transactionRecovery;

    private RecoverConfig recoverConfig = new RecoverConfig();

    public void init() {
        transactionRecovery.setRecoverConfig(recoverConfig);
        try {
            MethodInvokingJobDetailFactoryBean recoverJobDetai = new MethodInvokingJobDetailFactoryBean();
            recoverJobDetai.setTargetObject(transactionRecovery);
            recoverJobDetai.setTargetMethod("recover");
            recoverJobDetai.setName("transactionRecoveryJob");
            recoverJobDetai.setConcurrent(false);
            recoverJobDetai.afterPropertiesSet();
            CronTriggerFactoryBean recoverTrigger = new CronTriggerFactoryBean();
            recoverTrigger.setBeanName("transactionRecoverTrigger");
            recoverTrigger.setCronExpression(recoverConfig.getCronExpression());
            recoverTrigger.setJobDetail(recoverJobDetai.getObject());
            recoverTrigger.afterPropertiesSet();
            scheduler.scheduleJob(recoverJobDetai.getObject(), recoverTrigger.getObject());
            scheduler.start();
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }
}
